import { ref, reactive, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useAuth } from '@/hooks/auth'
import { confirm } from '@/utils'
import { formDefApi } from '@/api/modules/flow/formDef'
import type { FormDef } from '@/api/modules/flow/formDef'
import { useFlowStore } from '@/stores/flow'

export function useFormDef() {
  const { hasFuncKey } = useAuth()

  const data = reactive({
    resp: { list: [] as any[], total: 0 },
    loading: false,
    page: { pageNum: 1, pageSize: 16 }
  })
  const handleQuery = () => {
    data.loading = true
    const page = { ...data.page, sort: {}, filter: {} }
    formDefApi.findPage(page).then(resp => {
      if (resp.success) {
        data.resp = resp.data
      }
      data.loading = false
    })
  }

  onMounted(() => {
    return handleQuery()
  })

  const refCreateForm = ref()
  const createFormVisible = ref(false)

  // 打开修改的窗口
  const handleOpenEditForm = (data: FormDef) => {
    createFormVisible.value = true
    refCreateForm.value.setFormData(data)
  }

  // 执行删除操作
  const handleDelete = (item: FormDef) => {
    confirm(
      `<div>删除表单将会彻底删除其所有版本，</div><div>同时删除对应流程的所有版本, 以及所产生的历史流程单据, </div><div>确定要删除表单[${item.formName}]吗?</div>`,
      () => {
        formDefApi.delete([item.formId]).then(resp => {
          if (resp.success) {
            handleQuery()
            ElMessage.success(`表单[ ${name} ]已删除`)
          } else {
            ElMessage.error(resp.message)
          }
        })
      }
    )
  }

  const router = useRouter()
  const handleDesign = (item: FormDef) => {
    router.push({ name: 'flw-def-form-design', query: { id: item.formId } })
  }

  const fs = useFlowStore()
  watch(
    () => fs.changeActive,
    () => {
      handleQuery()
    }
  )

  return {
    hasFuncKey,
    data,
    handleQuery,
    refCreateForm,
    createFormVisible,
    handleOpenEditForm,
    handleDelete,
    handleDesign
  }
}
